//
//  WBStatusListViewModel.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/5.
//  Copyright © 2018年 xzw. All rights reserved.
//

import Foundation
import SDWebImage

private let MaxPullupTryCount = 3

class WBStatusListViewModel {
    
    //上拉刷新错误次数
    var pullupErrorCount = 0
    
    //懒加载数组
    lazy var statusList : [WBStatusViewModel] = [WBStatusViewModel]()
    
    func loadStatus(isPullup:Bool,completed:@escaping(_ issuccess : Bool,_ hasMorePullup:Bool)->()){

        if isPullup && pullupErrorCount > MaxPullupTryCount {//上拉刷新超过MaxPullupTryCount，静止网络请求
            completed(true, false)
            return
        }
        
        //下拉刷新
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        
        //上拉加载
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
        WBNetworkManager.sharedInstance.getstatusList(since_id: since_id, max_id: max_id) { (response, issuccess) in
            
            //0.判断网络请求是否成功
            if !issuccess{
                //直接回调返回
                completed(false, false)
            }
            
            //1.字典转模型
            var array = [WBStatusViewModel]()
            for dic in response ?? []{
                //创建微博模型
                guard let model = WBStatus.yy_model(with: dic) else{
                    continue
                }
                //将model添加到数组
                array.append(WBStatusViewModel(model: model))
            }
            
            print("刷新 \(array.count) 数据 \(array)")
            
            if isPullup {//上拉刷新
                self.statusList += array //拼接数据到数组末尾
            }else
            {
                //追加数据
                self.statusList = array + self.statusList //拼接数据放到数组前面
            }
        
            if isPullup && array.count == 0{//上拉数据加载已经到底了
                self.pullupErrorCount += 1
                completed(issuccess, false)
            }else{
                //加载数据完成
                self.cacheSingleImage(list: array,finished: completed)
               // completed(issuccess,true)
            }
        }
    }
    //缓存单张图片，获取图片的大小
    private func cacheSingleImage(list: [WBStatusViewModel],finished:@escaping(_ issuccess : Bool,_ hasMorePullup:Bool)->()) {
        
        //调度组
        let group = DispatchGroup()
        
        //记录数据长度
        var length = 0
        
        //遍历数组，查找微博数据中有单张图像的，进行缓存
        for vm in list {
            
            //1.判断单张图片
            if vm.picURLs?.count != 1{
                continue
            }
            
            //2.获取图像模型
           guard let pic = vm.picURLs![0].thumbnail_pic,
                 let url = URL(string: pic) else {
                continue
            }
            
            //3.入组
            group.enter()
            
            //4.拿到单张图片的URL，开始下载图片，保存到沙盒，路径是url的md5
            SDWebImageManager.shared().imageDownloader?.downloadImage(with: url, options: [], progress: nil, completed: { (image, data, _, _) in
                
                if let data = data {
                    length += data.count
                    
                    //图像缓存成功，更新配图视图的大小
                    vm.updateSingleImageSize(image: image!)
                }
                //print("缓存的图像是 \(image) 长度 \(length)")
                group.leave() //出组
            })
        }

        //监听调度组
        group.notify(queue: DispatchQueue.main) {
            print("图片缓存完成 \(length / 1024) k")
            finished(true, true)
        }
    }
    
}
